package com.bsoft.hospitalchs.ui.childcase;

import android.content.Context;
import android.graphics.Bitmap;
import android.util.Log;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.bsoft.hospitalchs.R;
import com.bsoft.hospitalchs.api.SimpleCookieJar;
import com.bsoft.hospitalchs.base.BaseFragment;
import com.bsoft.hospitalchs.common.MyApplication;
import com.bsoft.hospitalchs.model.SearchResBean;
import com.bsoft.hospitalchs.utils.LogUtil;
import com.bsoft.hospitalchs.widget.PtrClassicFrameLayout;
import com.bsoft.hospitalchs.widget.PtrDefaultHandler;
import com.bsoft.hospitalchs.widget.PtrFrameLayout;
import com.bsoft.hospitalchs.widget.PtrHandler;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.List;

import butterknife.Bind;
import okhttp3.Cookie;

import static com.bsoft.hospitalchs.R.id.webview;

/**
 * Created by 泅渡者
 * Created on 2017/6/14.
 */

public class ChildCaseFragment extends BaseFragment<ChildCaseContract.Presenter> implements ChildCaseContract.View {


    @Bind(R.id.rotate_header_web_view_frame)
    PtrClassicFrameLayout mPtrFrame;
    @Bind(webview)
    WebView mWebView;
    WebSettings mWebSettings;
    private String Url = "";
    SearchResBean searchResBean;

    @Override
    public int onSetLayoutId() {
        return R.layout.fragment_case;
    }

    @Override
    public void initView() {
        this.createPresenter(new ChildCasePresenter(this, getActivity()));
        getData();
    }


    @Override
    public void hideLoading() {

    }

    @Override
    public void showLoadingDialog() {

    }

    private void getData() {
        Gson gson = new Gson();
        searchResBean = gson.fromJson(getActivity().getIntent().getStringExtra("SearchResBean").toString(), new TypeToken<SearchResBean>() {
        }.getType());
        Url = "http://"+MyApplication.getInstance().getIpconfig()+"/phis/list.html?empiid=" + searchResBean.getBody().getEMPIID();
        Log.e("ChildCaseFragment", Url + "");
        mWebView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);//取消滚动条
        synCookies(getActivity(), "http://" + MyApplication.getInstance().getIpconfig() + "/phis/logon/myApps");
        mWebSettings = mWebView.getSettings();
        //设置自适应屏幕，两者合用
        mWebSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小
        mWebSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小

        //缩放操作
        mWebSettings.setSupportZoom(false); //支持缩放，默认为true。是下面那个的前提。
        mWebSettings.setBuiltInZoomControls(false); //设置内置的缩放控件。若为false，则该WebView不可缩放
        mWebSettings.setDisplayZoomControls(false); //隐藏原生的缩放控件

        //其他细节操作
        mWebSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        mWebSettings.setAllowFileAccess(true); //设置可以访问文件
        mWebSettings.setLoadsImagesAutomatically(true); //支持自动加载图片
        mWebSettings.setDefaultTextEncodingName("utf-8");//设置编码格式
        mWebSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        mWebSettings.setJavaScriptEnabled(true);

        mWebView.setWebViewClient(new WebViewClient() {

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                Log.e("onPageStartedUrl",url);
                Url =url;

            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url.toLowerCase().startsWith("http://") || url.toLowerCase().startsWith("https://")) {
                    return false;
                }

                return true;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                mPtrFrame.refreshComplete();

                CookieManager cookieManager = CookieManager.getInstance();
                String CookieStr = cookieManager.getCookie(url);
                LogUtil.i("Cookies", "Cookies = " + CookieStr);
                super.onPageFinished(view, url);
            }

        });
        mPtrFrame.setLastUpdateTimeRelateObject(this);
        mPtrFrame.setPtrHandler(new PtrHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, mWebView, header);
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                updateData();
            }
        });
        mPtrFrame.setResistance(1.7f);
        mPtrFrame.setRatioOfHeaderHeightToRefresh(1.2f);
        mPtrFrame.setDurationToClose(200);
        mPtrFrame.setDurationToCloseHeader(1000);
        mPtrFrame.setPullToRefresh(true);
        mPtrFrame.setKeepHeaderWhenRefresh(true);
        mPtrFrame.postDelayed(new Runnable() {
            @Override
            public void run() {
                mPtrFrame.autoRefresh();
            }
        }, 100);
    }

    private void updateData() {
        Log.e("update Data,",Url);
        mWebView.loadUrl(Url);
    }

    @SuppressWarnings("deprecation")
    public void synCookies(Context context, String url) {
        CookieSyncManager.createInstance(context);
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        cookieManager.removeSessionCookie();// 移除
        SimpleCookieJar simpleCookieJar = new SimpleCookieJar();

        List<Cookie> cookies = simpleCookieJar.getCookieStore().getCookies();

        String str = "";
        for (Cookie cookie : cookies) {
            str = "JSESSIONID=" + cookie.value() + "; path=" + cookie.path() + "; domain=" + cookie.domain();
            Log.e("cookie", str);
        }
        cookieManager.setCookie(url, str);
        CookieSyncManager.getInstance().sync();
    }

}
